package dmt16.TelemetrySuit.Communication
{
	import dmt16.TelemetrySuit.Communication.PacketTypes.IPacket;
	import dmt16.TelemetrySuit.Communication.PacketTypes.PacketReader;
	
	import flash.errors.IOError;
	import flash.events.ProgressEvent;
	import flash.utils.ByteArray;

	public class SuitTransportLayer
	{
		private var _connection:PhysicalLayer;
		
		private var _readingPacket:Boolean=false;
		private var _packetLength:int=0;
		private var _p:Number=0;
		
		private static var instance:SuitTransportLayer;
		{
			instance=new SuitTransportLayer();
		}
		
		public static function connect(port:int=5336):void{
			instance._connection=new PhysicalLayer(port);
			instance._connection.addEventListener(ProgressEvent.SOCKET_DATA,_onSocketData);			
		}
		
		public static function get connected():Boolean{
			return true;//instance._connection.connected;
		}
		
		private static function _onSocketData(event:ProgressEvent):void
		{
			//trace("On socket data");
			var data:ByteArray=new ByteArray();
			data.length=instance._connection.bytesAvailable;
			instance._connection.readBytes(data);
			PacketReader.parseData(data);
			//PacketReader.parseData(instance._connection.readBytesAsByteArray());
		}
		
		public static function sendPacket(packet:IPacket):void
		{
			var B:ByteArray=packet.outputBinary();
			B.position=0;
			trace(B.length);
			trace(B.position);
			for(var x:int=0; x<B.length;x++){
				trace(x,B[x]);
			}
			instance._connection.writeBytes(B);
			instance._connection.flush();
		}
	}
}